<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
    <script type="text/javascript" src="../internal.js?04dbe7f0"></script>
    <link rel="stylesheet" type="text/css" href="video.css?0043553c"/>
</head>
<body>
<div class="wrapper">
    <div id="videoTab">
        <div id="tabHeads" class="tabhead">
            <span tabSrc="video" class="focus" data-content-id="video"><var id="lang_tab_insertV"></var></span>
            <span tabSrc="upload" style="display:none;" data-content-id="upload"><var
                id="lang_tab_uploadV"></var></span>
        </div>
        <div id="tabBodys" class="tabbody">
            <div id="video" class="panel focus">
                <table>
                    <tr>
                        <td><label for="videoUrl" class="url"><var id="lang_video_url"></var></label></td>
                        <td><input id="videoUrl" type="text"><a href="javascript:;" id="videoSelect"
                                                                style="display:none;">选择视频</a></td>
                    </tr>
                </table>
                <div style="padding:0 5px 5px 5px;color:#999;">
                    外链视频支持：优酷、腾讯视频、哔哩哔哩
                </div>
                <div id="preview"></div>
                <div id="videoInfo">
                    <fieldset>
                        <legend><var id="lang_video_size"></var></legend>
                        <table>
                            <tr>
                                <td><label for="videoWidth"><var id="lang_videoW"></var></label></td>
                                <td><input class="txt" id="videoWidth" type="text"/></td>
                            </tr>
                            <tr>
                                <td><label for="videoHeight"><var id="lang_videoH"></var></label></td>
                                <td><input class="txt" id="videoHeight" type="text"/></td>
                            </tr>
                        </table>
                    </fieldset>
                    <fieldset>
                        <legend>视频封面</legend>
                        <div id="videoPosterUploadArea">
                            <div id="videoPosterPreview" class="poster-preview">
                                <img id="videoPosterImg" src="" style="display:none;max-width:100%;max-height:80px;"/>
                                <span id="videoPosterPlaceholder" class="poster-placeholder">点击上传封面</span>
                            </div>
                            <div class="poster-btns">
                                <div id="videoPosterPickerBtn" class="poster-picker-btn">选择封面</div>
                                <div id="videoPosterRemoveBtn" class="poster-remove-btn" style="display:none;">删除封面</div>
                            </div>
                            <input type="hidden" id="videoPosterUrl" value=""/>
                        </div>
                    </fieldset>
                    <fieldset>
                        <legend><var id="lang_alignment"></var></legend>
                        <div id="videoFloat"></div>
                    </fieldset>
                </div>
            </div>
            <div id="upload" class="panel">
                <div id="upload_left">
                    <div id="queueList" class="queueList">
                        <div class="statusBar element-invisible">
                            <div class="progress">
                                <span class="text">0%</span>
                                <span class="percentage"></span>
                            </div>
                            <div class="info"></div>
                            <div class="btns">
                                <div id="filePickerBtn"></div>
                                <div class="uploadBtn"><var id="lang_start_upload"></var></div>
                            </div>
                        </div>
                        <div id="dndArea" class="placeholder">
                            <div class="filePickerContainer">
                                <div id="filePickerReady"></div>
                            </div>
                        </div>
                        <ul class="filelist element-invisible">
                            <li id="filePickerBlock" class="filePickerBlock"></li>
                        </ul>
                    </div>
                </div>
                <div id="uploadVideoInfo">
                    <fieldset>
                        <legend><var id="lang_upload_size"></var></legend>
                        <table>
                            <tr>
                                <td><label><var id="lang_upload_width"></var></label></td>
                                <td><input class="txt" id="upload_width" type="text"/></td>
                            </tr>
                            <tr>
                                <td><label><var id="lang_upload_height"></var></label></td>
                                <td><input class="txt" id="upload_height" type="text"/></td>
                            </tr>
                        </table>
                    </fieldset>
                    <fieldset>
                        <legend>视频封面</legend>
                        <div id="posterUploadArea">
                            <div id="posterPreview" class="poster-preview">
                                <img id="posterImg" src="" style="display:none;max-width:100%;max-height:80px;"/>
                                <span id="posterPlaceholder" class="poster-placeholder">点击上传封面</span>
                            </div>
                            <div class="poster-btns">
                                <div id="posterPickerBtn" class="poster-picker-btn">选择封面</div>
                                <div id="posterRemoveBtn" class="poster-remove-btn" style="display:none;">删除封面</div>
                            </div>
                            <input type="hidden" id="posterUrl" value=""/>
                        </div>
                    </fieldset>
                    <fieldset>
                        <legend><var id="lang_upload_alignment"></var></legend>
                        <div id="upload_alignment"></div>
                    </fieldset>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- jquery -->
<script type="text/javascript" src="../../third-party/jquery-1.10.2.js?25f4b625"></script>

<!-- webuploader -->
<script type="text/javascript" src="../../third-party/webuploader/webuploader.js?2e7e9092"></script>
<link rel="stylesheet" type="text/css" href="../../third-party/webuploader/webuploader.css?b8f06036">

<!-- video -->
<script type="text/javascript" src="video.js?d0851f73"></script>

<!-- 视频封面上传功能 -->
<script type="text/javascript">
(function() {
    var posterUploader = null;
    var posterUrl = '';
    var videoPosterUploader = null;
    var videoPosterUrl = '';
    
    // 初始化封面上传器（上传标签页）
    function initPosterUploader() {
        var $ = jQuery;
        var imageActionUrl = editor.getActionUrl(editor.getOpt('imageActionName'));
        var imageMaxSize = editor.getOpt('imageMaxSize') || 2048000; // 2MB
        var imageAllowFiles = editor.getOpt('imageAllowFiles') || ['.png', '.jpg', '.jpeg', '.gif', '.bmp'];
        
        if (!WebUploader.Uploader.support()) {
            alert('您的浏览器不支持文件上传，请升级浏览器');
            return;
        }
        
        posterUploader = WebUploader.create({
            pick: {
                id: '#posterPickerBtn',
                label: '选择封面',
                multiple: false
            },
            swf: '../../third-party/webuploader/Uploader.swf',
            server: imageActionUrl,
            fileVal: editor.getOpt('imageFieldName') || 'file',
            duplicate: false,
            fileSingleSizeLimit: imageMaxSize,
            headers: editor.getOpt('serverHeaders') || {},
            compress: false,
            accept: {
                title: 'Images',
                extensions: imageAllowFiles.join(',').replace(/\./g, ''),
                mimeTypes: 'image/*'
            }
        });
        
        // 文件加入队列后
        posterUploader.on('fileQueued', function(file) {
            // 创建缩略图
            posterUploader.makeThumb(file, function(error, src) {
                if (error) {
                    console.error('生成缩略图失败', error);
                    return;
                }
                
                $('#posterImg').attr('src', src).show();
                $('#posterPlaceholder').hide();
            }, 100, 80);
            
            // 自动上传
            posterUploader.upload();
        });
        
        // 上传成功
        posterUploader.on('uploadSuccess', function(file, response) {
            try {
                var res = typeof response === 'string' ? JSON.parse(response) : response;
                res = editor.getOpt('serverResponsePrepare') ? editor.getOpt('serverResponsePrepare')(res) : res;
                
                if (res.state === 'SUCCESS' || res.code === 200) {
                    // 兼容不同的响应格式
                    posterUrl = res.url || (res.data && res.data.url) || '';
                    console.log('Upload tab poster URL set to:', posterUrl);
                    $('#posterUrl').val(posterUrl);
                    $('#posterRemoveBtn').show();
                    
                    // 如果返回的是完整URL，直接使用；否则使用配置的前缀
                    if (!/^https?:\/\//.test(posterUrl)) {
                        var urlPrefix = editor.getOpt('imageUrlPrefix') || '';
                        var fullUrl = urlPrefix + posterUrl;
                        $('#posterImg').attr('src', fullUrl);
                    } else {
                        $('#posterImg').attr('src', posterUrl);
                    }
                    
                    editor.fireEvent('uploadsuccess', {
                        res: res,
                        type: 'video-poster'
                    });
                } else {
                    alert('封面上传失败: ' + (res.message || res.state || '未知错误'));
                }
            } catch (e) {
                console.error('解析上传结果失败', e);
                alert('封面上传失败，请重试');
            }
        });
        
        // 上传失败
        posterUploader.on('uploadError', function(file, reason) {
            console.error('上传失败', reason);
            alert('封面上传失败，请重试');
        });
        
        // 上传之前
        posterUploader.on('uploadBeforeSend', function(obj, data, headers) {
            if (imageActionUrl.toLowerCase().indexOf('jsp') !== -1) {
                headers['X_Requested_With'] = 'XMLHttpRequest';
            }
        });
        
        // 文件验证错误
        posterUploader.on('error', function(type) {
            switch (type) {
                case 'F_EXCEED_SIZE':
                    alert('封面文件大小超出限制（最大' + (imageMaxSize / 1024 / 1024).toFixed(1) + 'MB）');
                    break;
                case 'Q_TYPE_DENIED':
                    alert('不支持的封面文件格式，请上传图片文件');
                    break;
                default:
                    alert('文件上传错误: ' + type);
            }
        });
    }
    
    // 初始化视频标签页封面上传器
    function initVideoPosterUploader() {
        var $ = jQuery;
        var imageActionUrl = editor.getActionUrl(editor.getOpt('imageActionName'));
        var imageMaxSize = editor.getOpt('imageMaxSize') || 2048000; // 2MB
        var imageAllowFiles = editor.getOpt('imageAllowFiles') || ['.png', '.jpg', '.jpeg', '.gif', '.bmp'];
        
        if (!WebUploader.Uploader.support()) {
            return;
        }
        
        videoPosterUploader = WebUploader.create({
            pick: {
                id: '#videoPosterPickerBtn',
                label: '选择封面',
                multiple: false
            },
            swf: '../../third-party/webuploader/Uploader.swf',
            server: imageActionUrl,
            fileVal: editor.getOpt('imageFieldName') || 'file',
            duplicate: false,
            fileSingleSizeLimit: imageMaxSize,
            headers: editor.getOpt('serverHeaders') || {},
            compress: false,
            accept: {
                title: 'Images',
                extensions: imageAllowFiles.join(',').replace(/\./g, ''),
                mimeTypes: 'image/*'
            }
        });
        
        // 文件加入队列后
        videoPosterUploader.on('fileQueued', function(file) {
            // 创建缩略图
            videoPosterUploader.makeThumb(file, function(error, src) {
                if (error) {
                    console.error('生成缩略图失败', error);
                    return;
                }
                
                $('#videoPosterImg').attr('src', src).show();
                $('#videoPosterPlaceholder').hide();
            }, 100, 80);
            
            // 自动上传
            videoPosterUploader.upload();
        });
        
        // 上传成功
        videoPosterUploader.on('uploadSuccess', function(file, response) {
            try {
                var res = typeof response === 'string' ? JSON.parse(response) : response;
                res = editor.getOpt('serverResponsePrepare') ? editor.getOpt('serverResponsePrepare')(res) : res;
                
                if (res.state === 'SUCCESS' || res.code === 200) {
                    videoPosterUrl = res.url || (res.data && res.data.url) || '';
                    console.log('Video tab poster URL set to:', videoPosterUrl);
                    $('#videoPosterUrl').val(videoPosterUrl);
                    $('#videoPosterRemoveBtn').show();
                    
                    if (!/^https?:\/\//.test(videoPosterUrl)) {
                        var urlPrefix = editor.getOpt('imageUrlPrefix') || '';
                        var fullUrl = urlPrefix + videoPosterUrl;
                        $('#videoPosterImg').attr('src', fullUrl);
                    } else {
                        $('#videoPosterImg').attr('src', videoPosterUrl);
                    }
                    
                    editor.fireEvent('uploadsuccess', {
                        res: res,
                        type: 'video-poster'
                    });
                } else {
                    alert('封面上传失败: ' + (res.message || res.state || '未知错误'));
                }
            } catch (e) {
                console.error('解析上传结果失败', e);
                alert('封面上传失败，请重试');
            }
        });
        
        // 上传失败
        videoPosterUploader.on('uploadError', function(file, reason) {
            console.error('上传失败', reason);
            alert('封面上传失败，请重试');
        });
        
        // 上传之前
        videoPosterUploader.on('uploadBeforeSend', function(obj, data, headers) {
            if (imageActionUrl.toLowerCase().indexOf('jsp') !== -1) {
                headers['X_Requested_With'] = 'XMLHttpRequest';
            }
        });
        
        // 文件验证错误
        videoPosterUploader.on('error', function(type) {
            switch (type) {
                case 'F_EXCEED_SIZE':
                    alert('封面文件大小超出限制（最大' + (imageMaxSize / 1024 / 1024).toFixed(1) + 'MB）');
                    break;
                case 'Q_TYPE_DENIED':
                    alert('不支持的封面文件格式，请上传图片文件');
                    break;
                default:
                    alert('文件上传错误: ' + type);
            }
        });
    }
    
    // 点击预览区域也可以选择文件
    $(document).ready(function() {
        // 上传标签页的封面上传
        $('#posterPreview').on('click', function() {
            $('#posterPickerBtn').click();
        });
        
        $('#posterRemoveBtn').on('click', function(e) {
            e.stopPropagation();
            posterUrl = '';
            $('#posterUrl').val('');
            $('#posterImg').attr('src', '').hide();
            $('#posterPlaceholder').show();
            $(this).hide();
        });
        
        // 视频标签页的封面上传
        $('#videoPosterPreview').on('click', function() {
            $('#videoPosterPickerBtn').click();
        });
        
        $('#videoPosterRemoveBtn').on('click', function(e) {
            e.stopPropagation();
            videoPosterUrl = '';
            $('#videoPosterUrl').val('');
            $('#videoPosterImg').attr('src', '').hide();
            $('#videoPosterPlaceholder').show();
            $(this).hide();
        });
    });
    
    // 等待页面加载完成后初始化
    window.addEventListener('load', function() {
        setTimeout(function() {
            initPosterUploader();
            initVideoPosterUploader();
        }, 500);
    });
    
    // 视频文件对应的封面映射 {videoUrl: posterUrl}
    var videoPosterMap = {};
    
    // 保存原始的execCommand方法
    var originalExecCommand = editor.execCommand;
    var isIntercepting = false; // 防止递归标志
    
    // 全局拦截insertvideo命令，添加poster属性
    editor.execCommand = function(cmdName, data, uploadType) {
        if (cmdName === 'insertvideo' && !isIntercepting) {
            isIntercepting = true;
            
            try {
                // 获取当前选中的tab
                var currentTab = '';
                var tabHeads = document.getElementById('tabHeads');
                if (tabHeads) {
                    var tabs = tabHeads.children;
                    for (var i = 0; i < tabs.length; i++) {
                        if (tabs[i].className && tabs[i].className.indexOf('focus') !== -1) {
                            currentTab = tabs[i].getAttribute('data-content-id');
                            break;
                        }
                    }
                }
                
                // 获取当前面板的默认封面URL
                var defaultPosterUrl = '';
                var $ = jQuery;
                if (currentTab === 'upload') {
                    defaultPosterUrl = posterUrl || ($('#posterUrl').length ? $('#posterUrl').val() : '') || '';
                } else if (currentTab === 'video') {
                    defaultPosterUrl = videoPosterUrl || ($('#videoPosterUrl').length ? $('#videoPosterUrl').val() : '') || '';
                }
                
                // 确保poster URL是完整的URL
                if (defaultPosterUrl && !/^https?:\/\//.test(defaultPosterUrl)) {
                    var urlPrefix = editor.getOpt('imageUrlPrefix') || '';
                    defaultPosterUrl = urlPrefix + defaultPosterUrl;
                }
                
                console.log('Current Tab:', currentTab, 'Default Poster URL:', defaultPosterUrl);
                console.log('Video Poster Map:', videoPosterMap);
                
                // 为视频数据添加poster属性
                if (Array.isArray(data)) {
                    // 多个视频
                    data.forEach(function(video, index) {
                        if (video && typeof video === 'object') {
                            // 优先使用该视频特定的封面，其次使用默认封面
                            var videoUrl = video.url || '';
                            var videoPoster = videoPosterMap[videoUrl] || defaultPosterUrl;
                            
                            if (videoPoster) {
                                video.poster = videoPoster;
                                console.log('Added poster to video [' + index + ']:', video);
                            }
                        }
                    });
                } else if (data && typeof data === 'object') {
                    // 单个视频
                    var videoUrl = data.url || '';
                    var videoPoster = videoPosterMap[videoUrl] || defaultPosterUrl;
                    
                    if (videoPoster) {
                        data.poster = videoPoster;
                        console.log('Added poster to video:', data);
                    }
                }
            } catch (e) {
                console.error('Error adding poster:', e);
            } finally {
                isIntercepting = false;
            }
        }
        
        // 调用原始方法
        return originalExecCommand.apply(editor, arguments);
    };
})();
</script>
</body>
</html>
